<template>
  <div class="user-container">
    <div class="user-layout">
      <!-- 左侧部门树 -->
      <aside class="department-tree-wrapper">
        <DepartmentTree
          ref="departmentTreeRef"
          :selected-id="queryForm.did"
          @select-department="handleDepartmentSelect"
        />
      </aside>

      <!-- 右侧内容区域 -->
      <main class="user-content-wrapper">
        <!-- 添加header栏 -->
        <el-card class="user-header">
          <template #header>
            <div class="card-header">
              <h3>企业员工管理</h3>
              <el-button type="success" @click="handleAdd">+ 新增用户</el-button>
            </div>
          </template>

          <el-form :model="queryForm" ref="queryFormRef" :inline="true" label-width="80px">
            <el-form-item label="关键词">
              <el-input
                v-model="queryForm.keywords"
                placeholder="姓名/用户名/手机号"
                clearable
                @keyup.enter="handleSearch"
                class="search-input"
              />
            </el-form-item>
            <el-form-item label="员工状态">
              <el-select
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
                class="search-select"
              >
                <el-option label="待入职" value="-1"></el-option>
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
                <el-option label="离职" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="员工类型">
              <el-select
                v-model="queryForm.type"
                placeholder="请选择类型"
                clearable
                class="search-select"
              >
                <el-option label="未设置" value="0"></el-option>
                <el-option label="正式员工" value="1"></el-option>
                <el-option label="试用员工" value="2"></el-option>
                <el-option label="实习员工" value="3"></el-option>
              </el-select>
            </el-form-item>
            <!-- 隐藏部门选择器，改为使用部门树 -->
            <el-form-item label="部门" v-if="false">
              <el-select v-model="queryForm.did" placeholder="请选择部门" clearable>
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.id"
                  :label="dept.title"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 用户列表保持不变 -->
        <el-card class="user-content">
          <div class="table-container">
            <el-table :data="userList" border v-loading="loading" style="width: 100%" height="500">
              <el-table-column prop="id" label="ID" width="50" fixed="left" />
              <el-table-column prop="name" label="姓名" width="100" fixed="left" />
              <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip />
              <el-table-column
                prop="department"
                label="主属部门"
                width="140"
                show-overflow-tooltip
              />
              <el-table-column
                prop="position_name"
                label="岗位"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column prop="mobile" label="手机号" width="120" />
              <el-table-column
                prop="entry_time"
                label="入职日期"
                width="120"
                :formatter="formatEntryTime"
              />
              <el-table-column
                prop="last_login_time"
                label="最后登录时间"
                width="170"
                :formatter="formatLastLoginTime"
              />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                  <el-tag v-if="scope.row.status === -1" type="info">待入职</el-tag>
                  <el-tag v-else-if="scope.row.status === 1" type="success">正常</el-tag>
                  <el-tag v-else-if="scope.row.status === 0" type="danger">禁用</el-tag>
                  <el-tag v-else-if="scope.row.status === 2" type="warning">离职</el-tag>
                  <el-tag v-else>未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleView(scope.row)">查看</el-button>
                  <el-dropdown @command="handleCommand">
                    <el-button size="small">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ action: 'edit', row: scope.row }">
                          编辑
                        </el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'resetPwd', row: scope.row }">
                          重置密码
                        </el-dropdown-item>
                        <el-dropdown-item
                          :command="{ action: 'disable', row: scope.row }"
                          v-if="
                            (scope.row.status === 1 || scope.row.status === -1) &&
                            scope.row.id !== 1
                          "
                        >
                          禁用
                        </el-dropdown-item>
                        <el-dropdown-item
                          :command="{ action: 'enable', row: scope.row }"
                          v-if="scope.row.status === 0 && scope.row.id !== 1"
                        >
                          启用
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="queryForm.page"
              v-model:page-size="queryForm.limit"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </main>
    </div>

    <!-- 用户详情抽屉 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      :title="drawerTitle"
      size="50%"
      @confirm="handleSave"
      :show-footer-buttons="currentAction !== 'view'"
    >
      <div class="drawer-content-wrapper">
        <el-form
          :model="detailForm"
          :rules="detailRules"
          ref="detailFormRef"
          label-width="100px"
          :disabled="currentAction === 'view'"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="detailForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="detailForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="部门类型">
            <el-radio-group v-model="departmentType" @change="loadOptions">
              <el-radio :label="1">内部部门</el-radio>
              <el-radio :label="2">外部律所</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="主属部门" prop="did">
            <el-cascader
              v-model="detailForm.did"
              :options="departmentTreeOptions"
              :props="cascaderProps"
              placeholder="请选择主属部门"
              clearable
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="其他部门">
            <el-cascader
              v-model="detailForm.department_ids"
              :options="departmentTreeOptions"
              :props="cascaderMultipleProps"
              placeholder="请选择其他部门"
              clearable
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="岗位" prop="position_id">
            <el-select v-model="detailForm.position_id" placeholder="请选择岗位">
              <el-option
                v-for="position in positionOptions"
                :key="position.id"
                :label="position.title"
                :value="position.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="detailForm.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="detailForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="入职时间" prop="entry_time">
            <el-date-picker
              v-model="detailForm.entry_time"
              type="date"
              placeholder="请选择入职时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, computed } from 'vue'
  import { useUserStore } from '@/store'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import DepartmentTree from './components/DepartmentTree.vue'
  import { GlobalDrawer } from '@/components/common'
  import { userApi } from '@/api/user'

  interface User {
    id: number
    name: string
    username: string
    nickname: string
    sex: number
    mobile: string
    email: string
    did?: number | null
    department_ids: string | number[] | undefined
    position_id?: number | null
    entry_time: string
    reg_pwd: string
    [key: string]: any
  }

  interface Department {
    id: number
    title: string
    [key: string]: any
  }

  interface Position {
    id: number
    title: string
    [key: string]: any
  }

  const userStore = useUserStore()

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
    status: '',
    type: '',
    did: null as number | null,
  })

  // 详情表单
  const detailForm = reactive({
    id: 0,
    name: '',
    username: '',
    nickname: '',
    sex: 1,
    mobile: '',
    email: '',
    did: null as number | null,
    department_ids: [] as number[] | string,
    position_id: null as number | null,
    entry_time: '',
    reg_pwd: '',
  })

  // 部门类型筛选
  const departmentType = ref(1) //  1-内部部门, 2-外部律所

  // 表单验证规则
  const detailRules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    did: [{ required: true, message: '请选择主属部门', trigger: 'change' }],
    position_id: [{ required: true, message: '请选择岗位', trigger: 'change' }],
    mobile: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    ],
    entry_time: [{ required: true, message: '请选择入职时间', trigger: 'change' }],
  }

  // 数据相关
  const userList = ref<User[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 抽屉相关
  const detailDrawerVisible = ref(false)
  const drawerTitle = ref('新增用户')
  const currentAction = ref('add') // 'add', 'edit', 'view'

  // 选项数据
  const departmentOptions = ref<Department[]>([])
  const positionOptions = ref<Position[]>([])

  // 过滤后的选项数据
  const filteredDepartmentOptions = computed(() => {
    if (departmentType.value === 0) {
      return departmentOptions.value
    }
    return departmentOptions.value.filter(dept => dept.type === departmentType.value)
  })

  const filteredPositionOptions = computed(() => {
    // 不再过滤岗位选项，显示所有岗位
    return positionOptions.value
  })

  // 表单引用
  const detailFormRef = ref<FormInstance>()
  const queryFormRef = ref<FormInstance>()
  const departmentTreeRef = ref<InstanceType<typeof DepartmentTree> | null>(null)

  // 时间格式化函数
  const formatEntryTime = (row: any, column: any, cellValue: string) => {
    if (!cellValue || cellValue === '0') return '-'
    // Unix时间戳转JavaScript时间戳（秒转毫秒）
    const timestamp = parseInt(cellValue) * 1000
    const date = new Date(timestamp)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
  }

  const formatLastLoginTime = (row: any, column: any, cellValue: string) => {
    if (!cellValue || cellValue === '0') return '-'
    // Unix时间戳转JavaScript时间戳（秒转毫秒）
    const timestamp = parseInt(cellValue) * 1000
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false,
    })
  }

  // 查询用户列表
  const loadUserList = async () => {
    loading.value = true
    try {
      const res = await userStore.getUserListAction(queryForm)
      if (res.code === 0) {
        userList.value = res.data.list
        total.value = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取用户列表失败')
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    queryForm.page = 1
    loadUserList()
  }

  // 重置
  const handleReset = () => {
    queryForm.keywords = ''
    queryForm.status = ''
    queryForm.type = ''
    queryForm.did = null
    queryForm.page = 1

    // 重置部门树选择
    if (departmentTreeRef.value) {
      departmentTreeRef.value.setSelectedNode(null)
    }

    loadUserList()
  }

  // 添加用户
  const handleAdd = () => {
    currentAction.value = 'add'
    drawerTitle.value = '新增用户'
    // 重置表单
    Object.assign(detailForm, {
      id: 0,
      name: '',
      username: '',
      nickname: '',
      sex: 1,
      mobile: '',
      email: '',
      did: null,
      department_ids: [],
      position_id: null,
      entry_time: '',
      reg_pwd: '',
    })
    detailDrawerVisible.value = true
  }

  // 查看用户详情
  const handleView = (row: any) => {
    currentAction.value = 'view'
    drawerTitle.value = '查看用户'
    Object.assign(detailForm, row)
    // 处理department_ids为数组
    if (typeof row.department_ids === 'string' && row.department_ids) {
      detailForm.department_ids = row.department_ids
        .split(',')
        .map((id: string) => parseInt(id, 10))
        .filter((id: number) => !isNaN(id))
    } else if (Array.isArray(row.department_ids)) {
      detailForm.department_ids = row.department_ids
        .map((id: any) => (typeof id === 'string' ? parseInt(id, 10) : id))
        .filter((id: number) => !isNaN(id))
    } else {
      detailForm.department_ids = []
    }

    // 确保 did 和 position_id 是数字或 null
    detailForm.did = row.did ? parseInt(row.did, 10) : null
    detailForm.position_id = row.position_id ? parseInt(row.position_id, 10) : null

    detailDrawerVisible.value = true
  }

  // 编辑用户
  const handleEdit = (row: any) => {
    currentAction.value = 'edit'
    drawerTitle.value = '编辑用户'
    Object.assign(detailForm, row)
    // 处理department_ids为数组
    if (typeof row.department_ids === 'string' && row.department_ids) {
      detailForm.department_ids = row.department_ids
        .split(',')
        .map((id: string) => parseInt(id, 10))
        .filter((id: number) => !isNaN(id))
    } else if (Array.isArray(row.department_ids)) {
      detailForm.department_ids = row.department_ids
        .map((id: any) => (typeof id === 'string' ? parseInt(id, 10) : id))
        .filter((id: number) => !isNaN(id))
    } else {
      detailForm.department_ids = []
    }

    // 确保 did 和 position_id 是数字或 null
    detailForm.did = row.did ? parseInt(row.did, 10) : null
    detailForm.position_id = row.position_id ? parseInt(row.position_id, 10) : null

    detailDrawerVisible.value = true
  }

  // 保存用户
  const handleSave = () => {
    if (!detailFormRef.value) return

    detailFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 处理department_ids为字符串
          let formData: any = { ...detailForm }
          if (Array.isArray(formData.department_ids) && formData.department_ids.length > 0) {
            formData.department_ids = formData.department_ids.join(',')
          } else if (!formData.department_ids) {
            formData.department_ids = '' // 如果为空数组或未定义，设置为空字符串
          }

          // 确保数字字段正确
          if (formData.did !== null && formData.did !== undefined) {
            formData.did = parseInt(formData.did, 10)
          } else {
            formData.did = null
          }

          if (formData.position_id !== null && formData.position_id !== undefined) {
            formData.position_id = parseInt(formData.position_id, 10)
          } else {
            formData.position_id = null
          }

          // 处理入职时间
          if (formData.entry_time) {
            // 确保是有效的日期格式
            const date = new Date(formData.entry_time)
            if (!isNaN(date.getTime())) {
              formData.entry_time = date.toISOString().split('T')[0]
            }
          }

          let res: any
          if (currentAction.value === 'add') {
            // 新增用户
            res = await userStore.addUserAction(formData)
          } else {
            // 编辑用户
            res = await userStore.editUserAction(formData)
          }

          if (res.code === 0) {
            ElMessage.success(res.msg || '保存成功')
            detailDrawerVisible.value = false
            loadUserList()
          } else {
            ElMessage.error(res.msg || '保存失败')
          }
        } catch (error) {
          ElMessage.error('保存失败')
        }
      }
    })
  }

  // 重置密码
  const handleResetPassword = (row: any) => {
    ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await userStore.resetUserPasswordAction({ id: row.id })
          if (res.code === 0) {
            ElMessage.success(res.msg || '重置密码成功')
          } else {
            ElMessage.error(res.msg || '重置密码失败')
          }
        } catch (error) {
          ElMessage.error('重置密码失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 禁用用户
  const handleDisable = (row: any) => {
    ElMessageBox.confirm('确定要禁用该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await userStore.setUserStatusAction({ id: row.id, status: 0 })
          if (res.code === 0) {
            ElMessage.success(res.msg || '禁用成功')
            loadUserList()
          } else {
            ElMessage.error(res.msg || '禁用失败')
          }
        } catch (error) {
          ElMessage.error('禁用失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 启用用户
  const handleEnable = (row: any) => {
    ElMessageBox.confirm('确定要启用该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await userStore.setUserStatusAction({ id: row.id, status: 1 })
          if (res.code === 0) {
            ElMessage.success(res.msg || '启用成功')
            loadUserList()
          } else {
            ElMessage.error(res.msg || '启用失败')
          }
        } catch (error) {
          ElMessage.error('启用失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 处理下拉菜单命令
  const handleCommand = (command: any) => {
    const { action, row } = command
    switch (action) {
      case 'edit':
        handleEdit(row)
        break
      case 'resetPwd':
        handleResetPassword(row)
        break
      case 'disable':
        handleDisable(row)
        break
      case 'enable':
        handleEnable(row)
        break
    }
  }

  // 分页相关
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1
    loadUserList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    loadUserList()
  }

  // 部门树形选择器配置
  const cascaderProps = {
    value: 'id',
    label: 'title',
    children: 'children',
    emitPath: false,
    checkStrictly: true,
  }

  const cascaderMultipleProps = {
    value: 'id',
    label: 'title',
    children: 'children',
    emitPath: false,
    checkStrictly: true,
    multiple: true,
  }

  // 部门树形选项
  const departmentTreeOptions = computed(() => {
    // 将扁平的部门数据转换为树形结构
    const buildTree = (data: Department[], pid: number = 0): Department[] => {
      return data
        .filter(item => item.pid === pid)
        .map(item => ({
          ...item,
          children: buildTree(data, item.id),
        }))
    }

    return buildTree(departmentOptions.value)
  })

  // 修复部门加载错误：先获取部门数据，再构建树
  const loadOptions = async () => {
    try {
      // 加载部门选项（用于下拉选择）
      const deptRes = await userStore.getDepartmentOptionsAction()
      if (deptRes.code === 0) {
        // 确保departmentOptions包含完整的部门数据，并过滤掉id为null或undefined的项
        const deptData = Array.isArray(deptRes.data) ? deptRes.data : []
        departmentOptions.value = deptData.filter(
          (dept: Department) => dept.id !== null && dept.id !== undefined
        )
      }

      // 加载岗位选项（用于下拉选择）- 使用与员工档案相同的接口
      const positionRes: any = await userApi.getPositionOptions()
      if (positionRes.code === 0) {
        // 后端返回的数据格式是 {list: []}，需要从 data.list 中获取
        const positionList = Array.isArray(positionRes.data?.list) ? positionRes.data.list : []
        // 过滤掉id为null或undefined的项
        positionOptions.value = positionList.filter(
          (position: Position) => position.id !== null && position.id !== undefined
        )
      }
    } catch (error) {
      ElMessage.error('加载选项数据失败')
      console.error('加载选项数据失败:', error)
    }
  }

  // 在onMounted之前添加watch逻辑
  // 监听主属部门变化，自动从其他部门中移除
  watch(
    () => detailForm.did,
    newDid => {
      if (newDid && Array.isArray(detailForm.department_ids)) {
        detailForm.department_ids = detailForm.department_ids.filter(id => id !== newDid)
      }
    }
  )

  // 监听其他部门变化，确保不包含主属部门
  watch(
    () => detailForm.department_ids,
    newDepartments => {
      if (Array.isArray(newDepartments) && detailForm.did) {
        const hasMainDept = newDepartments.includes(detailForm.did)
        if (hasMainDept) {
          detailForm.department_ids = newDepartments.filter(id => id !== detailForm.did)
          ElMessage.warning('主属部门已自动从其他部门中移除')
        }
      }
    },
    { deep: true }
  )

  // 初始化加载
  onMounted(() => {
    loadUserList()
    loadOptions()
  })

  // 处理部门树选择事件
  const handleDepartmentSelect = (id: number | null) => {
    queryForm.did = id
    queryForm.page = 1
    loadUserList()
  }
</script>

<style scoped>
  .user-container {
    padding: 10px;
    height: calc(100vh - 60px);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden; /* 防止整体滚动 */
  }

  .user-layout {
    display: flex;
    flex: 1;
    min-height: 0;
    gap: 16px;
    height: 100%; /* 确保占满父容器高度 */
    overflow: hidden; /* 防止内容溢出 */
  }

  .department-tree-wrapper {
    width: 240px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .user-content-wrapper {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden; /* 确保内容不溢出 */
  }

  .user-header {
    margin-bottom: 12px;
    flex-shrink: 0; /* 防止搜索区域被压缩 */
    height: auto; /* 让内容决定高度 */
  }

  .user-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden; /* 确保不会溢出 */
  }

  .el-card.user-content :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    border-radius: 8px; /* 确保内容区域也有圆角 */
    overflow: hidden; /* 防止内容溢出 */
  }

  .table-container {
    flex: 1;
    overflow: auto; /* 同时支持横向和纵向滚动 */
    padding: 16px 20px 0 20px; /* 移除底部padding，让分页紧贴表格 */
    min-height: 200px; /* 设置最小高度 */
    background: #fafbfc; /* 添加轻微背景色区分 */
    position: relative; /* 提供定位上下文 */
    max-height: calc(100% - 60px); /* 确保留出分页的空间 */
    height: 0; /* 关键：强制容器计算高度并显示滚动条 */

    /* 优化滚动条样式 */
    scrollbar-width: thin;
    scrollbar-color: #c0c4cc #f5f7fa;
  }

  .table-container .el-table {
    width: 100% !important;
    min-width: unset;
    border-radius: 6px; /* 添加圆角 */
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); /* 轻微阴影 */
    background: white; /* 确保表格背景为白色 */
  }

  .pagination-container {
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center; /* 垂直居中对齐 */
    border-top: 1px solid #ebeef5;
    height: auto; /* 让内容决定高度 */
    min-height: 60px; /* 确保有足够的空间 */
    box-sizing: border-box;
    flex-shrink: 0; /* 防止分页被压缩 */
    background: white; /* 确保分页背景为白色 */
    position: sticky; /* 固定在底部 */
    bottom: 0; /* 固定在底部 */
    z-index: 10; /* 确保显示在内容之上 */
  }

  /* 添加header样式 */
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  /* 确保表格数据过多时依然能看到分页 */
  .el-card.user-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0; /* 关键：允许弹性布局计算实际高度 */
    max-height: none; /* 移除固定高度限制 */
    position: relative; /* 创建定位上下文 */
    overflow: hidden; /* 防止内容溢出 */
  }

  /* 确保横向滚动条在需要时显示 */
  .table-container .el-table__body-wrapper {
    overflow: auto !important;
    max-height: calc(100vh - 280px) !important; /* 设置最大高度以确保滚动条显示 */
    min-height: 150px !important; /* 确保即使数据很少也有合理高度 */
  }

  /* 确保表格容器可以正确显示滚动条 */
  .table-container .el-table {
    width: 100% !important;
    height: auto !important;
    table-layout: fixed !important; /* 提高渲染性能 */
  }

  /* 确保表格内容不被分页遮挡 */
  .table-container .el-table__body {
    margin-bottom: 10px;
  }

  /* 强制启用滚动条 */
  .el-table__body-wrapper::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    display: block !important; /* 强制显示滚动条 */
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #c0c4cc;
    border-radius: 4px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }

  /* 优化搜索栏控件宽度 */
  .search-input {
    width: 200px;
  }

  .search-select {
    width: 150px;
  }

  /* 优化表格滚动条 */
  .table-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .table-container::-webkit-scrollbar-track {
    background: #f5f7fa;
    border-radius: 3px;
  }

  .table-container::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  .table-container::-webkit-scrollbar-thumb:hover {
    background: #909399;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  /* 部门选择区域样式保持不变 */
  .department-section {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 16px;
    background-color: #f9fafc;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
  }

  .department-main,
  .department-additional {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .department-label {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    min-width: 70px;
    text-align: right;
  }

  .department-tips {
    margin-top: 4px;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .department-tree-wrapper {
      width: 220px;
    }
  }

  @media (max-width: 992px) {
    .user-layout {
      flex-direction: column;
      height: auto;
    }

    .department-tree-wrapper {
      width: 100%;
      height: 300px;
      margin-bottom: 16px;
    }

    .user-container {
      height: auto;
      min-height: calc(100vh - 60px);
    }
  }

  @media (max-width: 768px) {
    .user-container {
      padding: 10px;
    }

    .department-main,
    .department-additional {
      flex-direction: column;
      align-items: flex-start;
    }

    .department-label {
      text-align: left;
      margin-bottom: 4px;
    }

    .table-container {
      padding: 10px;
    }

    .pagination-container {
      padding: 10px;
    }
  }
</style>
